package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.Counselor;
import com.example.chamberlainserver.Service.CounselorService;
import com.example.chamberlainserver.dto.CounselorDTO;
import com.example.chamberlainserver.dto.CounselorPermissions;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.CounselorMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 辅导员服务实现类
 */
@Service
@Transactional
public class CounselorServiceImpl implements CounselorService {

    @Autowired
    private CounselorMapper counselorMapper;

    @Override
    public List<Counselor> getAllCounselors() {
        return counselorMapper.selectAll();
    }

    @Override
    public Counselor getCounselorById(Long id) {
        return counselorMapper.selectById(id.intValue());
    }

    @Override
    public Counselor getCounselorByEmployeeId(String employeeId) {
        return counselorMapper.selectByEmployeeId(employeeId);
    }

    @Override
    public PageResult<Counselor> getCounselorsByPage(int page, int size, String name, String department, Integer status) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 查询数据
        String statusStr = status != null ? status.toString() : null;
        List<Counselor> counselors = counselorMapper.selectByPage(offset, size, name, department, statusStr);
        
        // 查询总数
        int total = counselorMapper.countAll(name, department, statusStr);
        
        return new PageResult<>(page, size, (long) total, counselors);
    }



    @Override
    public Counselor createCounselor(CounselorDTO counselorDTO) {
        // 验证工号唯一性
        if (counselorMapper.selectByEmployeeId(counselorDTO.getEmployeeId()) != null) {
            throw new RuntimeException("工号已存在");
        }
        
        // 邮箱和手机号验证暂时跳过，因为mapper中没有对应方法
        
        Counselor counselor = new Counselor();
        BeanUtils.copyProperties(counselorDTO, counselor);
        counselor.setCreateTime(LocalDateTime.now());
        counselor.setUpdateTime(LocalDateTime.now());
        
        // 设置默认值
        if (counselor.getStatus() == null) {
            counselor.setStatus("在职");
        }
        if (counselor.getPermissionsJson() == null) {
            counselor.setPermissions(CounselorPermissions.createDefault());
        }
        
        counselorMapper.insert(counselor);
        return counselor;
    }

    @Override
    public Counselor updateCounselor(Long id, CounselorDTO counselorDTO) {
        Counselor existingCounselor = counselorMapper.selectById(id.intValue());
        if (existingCounselor == null) {
            throw new RuntimeException("辅导员不存在");
        }
        
        // 验证工号唯一性（排除自己）
        Counselor counselorWithSameEmployeeId = counselorMapper.selectByEmployeeId(counselorDTO.getEmployeeId());
        if (counselorWithSameEmployeeId != null) {
            throw new RuntimeException("工号已存在");
        }
        
        // 邮箱和手机号验证暂时跳过，因为mapper中没有对应方法
        
        BeanUtils.copyProperties(counselorDTO, existingCounselor, "id", "createTime");
        existingCounselor.setUpdateTime(LocalDateTime.now());
        
        counselorMapper.update(existingCounselor);
        return existingCounselor;
    }

    @Override
    public boolean deleteCounselor(Long id) {
        Counselor counselor = counselorMapper.selectById(id.intValue());
        if (counselor == null) {
            return false;
        }
        
        return counselorMapper.deleteById(id.intValue()) > 0;
    }

    @Override
    public int deleteCounselors(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        List<Integer> intIds = new ArrayList<>();
        for (Long id : ids) {
            intIds.add(id.intValue());
        }
        return counselorMapper.deleteByIds(intIds);
    }

    @Override
    public List<Counselor> getCounselorsByClassId(Long classId) {
        return counselorMapper.selectByClassId(classId.intValue());
    }

    @Override
    public List<Counselor> getUnassignedCounselors() {
        return counselorMapper.selectUnassigned();
    }

    @Override
    public boolean updateCounselorStatus(Long id, Integer status) {
        Counselor counselor = counselorMapper.selectById(id.intValue());
        if (counselor == null) {
            return false;
        }
        counselor.setStatus(status.toString());
        counselor.setUpdateTime(LocalDateTime.now());
        return counselorMapper.update(counselor) > 0;
    }

    @Override
    public boolean updateCounselorPermissions(Long id, String permissions) {
        Counselor counselor = counselorMapper.selectById(id.intValue());
        if (counselor == null) {
            return false;
        }
        
        try {
            // 尝试解析JSON字符串为权限对象
            ObjectMapper objectMapper = new ObjectMapper();
            CounselorPermissions permissionsObj = objectMapper.readValue(permissions, CounselorPermissions.class);
            counselor.setPermissions(permissionsObj);
        } catch (JsonProcessingException e) {
            // 如果解析失败，直接设置JSON字符串
            counselor.setPermissionsJson(permissions);
        }
        
        counselor.setUpdateTime(LocalDateTime.now());
        
        return counselorMapper.update(counselor) > 0;
    }

    @Override
    public boolean isEmployeeIdUnique(String employeeId, Long excludeId) {
        Counselor existingCounselor = counselorMapper.selectByEmployeeId(employeeId);
        if (existingCounselor == null) {
            return true;
        }
        return excludeId != null && existingCounselor.getId().equals(excludeId.intValue());
    }

    @Override
    public boolean isEmailUnique(String email, Long excludeId) {
        // 暂时返回true，因为mapper中没有对应方法
        return true;
    }

    @Override
    public boolean isPhoneUnique(String phone, Long excludeId) {
        // 暂时返回true，因为mapper中没有对应方法
        return true;
    }
}